package com.sansecy.customview.view.calendar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import androidx.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.sansecy.customview.DensityUtils;
import com.sansecy.customview.view.calendar.bean.SignDateBean;
import com.sansecy.customview.view.calendar.calendarhelper.CalendarConstant;
import com.sansecy.customview.view.calendar.calendarhelper.CalendarModel;
import com.sansecy.customview.view.calendar.calendarhelper.CalendarUtil;
import com.sansecy.customview.view.calendar.calendarhelper.LunarCalendar;
import com.sansecy.customview.view.calendar.calendarhelper.SolarTermUtil;

import java.text.ParseException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * @Description 月日历视图
 * @Date 2019-08-20 23:04
 * @Created by caoyu
 */
public class MonthCalendarBottomBgView extends View {

    public static final String SIGNED = "signed";
    public static int DATE_SIZE = 20;
    public static int LUNAR_SIZE = 11;
    //    private Paint mWeekPaint;
    private TextPaint mPastTextPaint;
    private TextPaint mTextPaint;
    private List<CalendarModel> mCalendarModels;
    private int mCurrentMonth;
    private int mCurrentDay;
    private Paint mSchemePaint;
    private Paint mLunarPaint;
    private float mLunarAscent;
    private int mSchemeRatio = 5;
    private Paint mTestPaint;
    private int mDp4;
    private int mDp8;
    private int mDp15;

    public MonthCalendarBottomBgView(Context context) {
        this(context, null);
    }

    public MonthCalendarBottomBgView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

//        mWeekPaint = new Paint();
//        mWeekPaint.setColor(Color.BLACK);
//        mWeekPaint.setAntiAlias(true);
//        mWeekPaint.setTextSize(sp2px(DATE_SIZE));

        SolarTermUtil.init(getContext());
        LunarCalendar.init(getContext());
        mDp4 = DensityUtils.dp2px(context, 4.5f);
        mDp8 = DensityUtils.dp2px(context, 8f);
        mDp15 = DensityUtils.dp2px(context, 15);
        Calendar instance = Calendar.getInstance(Locale.getDefault());
        int year = instance.get(Calendar.YEAR);
        mCurrentMonth = instance.get(Calendar.MONTH) + 1;
        mCurrentDay = instance.get(Calendar.DAY_OF_MONTH);
        CalendarModel calendarModel = new CalendarModel();
        calendarModel.setYear(year);
        calendarModel.setMonth(mCurrentMonth);
        calendarModel.setDay(mCurrentDay);
        mCalendarModels = CalendarUtil.initCalendarForMonthView(year, mCurrentMonth, calendarModel, CalendarConstant.WEEK_START_WITH_MON);

        //这个日历默认返回6行
        //取倒数第7个，判断是否不是当月，不是当月的话，直接去掉后面7天，给绘图留出空间

        CalendarModel model = mCalendarModels.get(mCalendarModels.size() - 8);
        if (model.getMonth() != mCurrentMonth) {
            for (int i = 0; i < 7; i++) {
                mCalendarModels.remove(mCalendarModels.size() - 1);
            }
            DATE_SIZE = 20;
            mSchemeRatio = 6;
        }

        mPastTextPaint = new TextPaint();
        mPastTextPaint.setColor(Color.parseColor("#dddddd"));
        mPastTextPaint.setTextAlign(Paint.Align.CENTER);
        mPastTextPaint.setAntiAlias(true);
        mPastTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
        mPastTextPaint.setTextSize(sp2px(DATE_SIZE));

        mSchemePaint = new Paint();
        mSchemePaint.setStyle(Paint.Style.FILL);
        mSchemePaint.setAntiAlias(true);
        mSchemePaint.setColor(Color.parseColor("#4972F9"));
        mSchemePaint.setStrokeWidth(5);

        mTextPaint = new TextPaint();
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(sp2px(DATE_SIZE));

        mLunarPaint = new Paint();
        mLunarPaint.setAntiAlias(true);
        mLunarPaint.setTextAlign(Paint.Align.CENTER);
        mLunarPaint.setColor(Color.parseColor("#999999"));
        mLunarPaint.setTextSize(sp2px(LUNAR_SIZE));
        mLunarPaint.setStrokeWidth(20);
        mLunarAscent = Math.abs(mLunarPaint.ascent()) + Math.abs(mLunarPaint.descent());

        mTestPaint = new Paint();
//        mTestPaint.setStyle(Paint.Style.STROKE);
        mTestPaint.setStrokeWidth(mDp15);
        mTestPaint.setStrokeCap(Paint.Cap.ROUND);
        mTestPaint.setColor(Color.parseColor("#BBD8FC"));

    }

    private void drawStrokeCap(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStrokeWidth(100);

        paint.setColor(Color.parseColor("#000099"));
        canvas.drawLine(100, 100, 400, 100, paint);

        paint.setAntiAlias(true);

        paint.setColor(Color.parseColor("#00ff00"));
        paint.setStrokeCap(Paint.Cap.BUTT);       // 线帽，即画的线条两端是否带有圆角，butt，无圆角
        canvas.drawLine(100, 200, 400, 200, paint);

        paint.setColor(Color.parseColor("#ff0000"));
        paint.setStrokeCap(Paint.Cap.ROUND);       // 线帽，即画的线条两端是否带有圆角，ROUND，圆角
        canvas.drawLine(100, 300, 400, 300, paint);

        paint.setColor(Color.parseColor("#0000ff"));
        paint.setStrokeCap(Paint.Cap.SQUARE);       // 线帽，即画的线条两端是否带有圆角，SQUARE，矩形
        canvas.drawLine(100, 400, 400, 400, paint);

    }

    int itemHeight;
    int count;
    private static final String TAG = "MonthCalendarBottomBgVi-App";

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //取得日历天数
        int size = mCalendarModels.size();
        //计算总共多少行
        int totalRows = size / 7;
        //取余看是不是多出几个
        if (size % 7 > 0) {
            //多出了再加一行
            totalRows++;
        }
        //得到视图宽度，分成7份
        int itemWidth = getContentWidth() / 7;
        //取每一份的一半，在这条线上画东西
        int halfItemWidth = itemWidth / 2;
        //定义每一块区域的高度
        int itemHeight = getContentHeight() / totalRows;
        //取中间值
        int halfItemHeight = itemHeight / 2;
        //根据宽高计算半径
        int radius = Math.max(halfItemWidth, halfItemHeight) / 10 * mSchemeRatio;

        int row = 0;
        //表示当前画到第几个了
        int position = 0;

        float descent = mTextPaint.descent();
        for (int i = 0; i < totalRows; i++) {
            //画横线

            for (int j = 0; j < 7; j++) {
                //画竖线
                if (position > size - 1) {
                    return;
                }

                CalendarModel calendarModel = mCalendarModels.get(position);
                String scheme = calendarModel.getScheme();

                if (calendarModel.getMonth() != mCurrentMonth) {
                    //不是当前月，文字显示灰色
                    if (scheme != null && scheme.equals(SIGNED)) {
                        //绘制阳历
                        canvas.drawLine(getContentStart() + itemWidth * j, halfItemHeight + itemHeight * i + descent, getContentStart() + itemWidth * (j + 1), halfItemHeight + itemHeight * i + descent, mTestPaint);
                        canvas.drawText(String.valueOf(calendarModel.getDay()), getContentStart() + halfItemWidth + itemWidth * j, halfItemHeight + itemHeight * i + descent, mPastTextPaint);
                    } else {
                        canvas.drawText(String.valueOf(calendarModel.getDay()), getContentStart() + halfItemWidth + itemWidth * j, halfItemHeight + itemHeight * i + descent, mPastTextPaint);
                    }
                } else {
                    float textY = halfItemHeight + itemHeight * i + descent;
                    if (scheme != null && scheme.equals(SIGNED)) {
                        //绘制阳历
                        canvas.drawLine(getContentStart() + itemWidth * j, halfItemHeight + itemHeight * i + descent, getContentStart() + itemWidth * (j + 1), halfItemHeight + itemHeight * i + descent, mTestPaint);
                        canvas.drawText(String.valueOf(calendarModel.getDay()), getContentStart() + halfItemWidth + itemWidth * j, textY, mTextPaint);
                    } else {
                        canvas.drawText(String.valueOf(calendarModel.getDay()), getContentStart() + halfItemWidth + itemWidth * j, textY, mTextPaint);
                    }
                    if (calendarModel.isCurrentDay()) {
                        canvas.drawCircle(getContentStart() + halfItemWidth + itemWidth * j, textY + mDp4 + mDp4, mDp4, mSchemePaint);
                    }
                    //当前月，文字默认黑色
                }
                position++;
            }
            row++;
        }
    }

    public int getContentStart() {
        return getPaddingLeft();
    }

    public int getContentWidth() {
        return getWidth() - getPaddingLeft() - getPaddingRight();
    }

    public int getContentHeight() {
        return getHeight() - getPaddingTop() - getPaddingBottom();
    }

    private static boolean isToday(long time) throws ParseException {
        Log.d(TAG, "isToday() called with: time = [" + time + "]");
        Long todayZeroPointTimestamps = getTodayZeroPointTimestamps();
        Log.d(TAG, "isToday() called with: todayZeroPointTimestamps = [" + todayZeroPointTimestamps + "]");
        if ((time - todayZeroPointTimestamps) < oneDayTimestamps) {  //今天
            return true;
        }
        return false;
    }

    /**
     * @Author:whf
     * @param:
     * @Description: 获得“今天”零点时间戳 获得2点的加上2个小时的毫秒数就行
     * @Date:2018/4/12 0012
     */
    public static Long getTodayZeroPointTimestamps() {
        Long currentTimestamps = System.currentTimeMillis();
        return currentTimestamps - (currentTimestamps + GT800) % oneDayTimestamps;
    }

    public static long oneDayTimestamps = 60 * 60 * 24 * 1000;
    private static long GT800 = 60 * 60 * 8 * 1000;


    public float sp2px(float size) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, getResources().getDisplayMetrics());
    }

    /**
     * dp转px
     *
     * @param dpValue dp
     * @return px
     */
    private int dpToPx(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void setSignedDays(List<SignDateBean> dates) {
        if (dates == null || dates.size() == 0) {
            return;
        }
        for (int i = 0; i < dates.size(); i++) {

            SignDateBean signDateBean = dates.get(i);
            Calendar calendar = Calendar.getInstance(Locale.getDefault());
            calendar.setTimeInMillis(signDateBean.getCheckinTime());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            for (int j = 0; j < mCalendarModels.size(); j++) {
                CalendarModel model = mCalendarModels.get(j);
                if (year == model.getYear() && month == model.getMonth() && day == model.getDay() &&
                        signDateBean.isShowBackground()) {
                    model.setScheme(SIGNED);
                    Log.d(TAG, "setSignedDays() called with: day = [" + day + "]");
                    break;
                }
            }

        }
        invalidate();
    }
}
